import { createGunzip } from 'zlib'

export const forEach = (arr, fn) => {
  if (!arr.length || !fn) return
  let i = -1
  const len = arr.length
  while (++i < len) {
    const item = arr[i]
    fn(item, i, arr)
  }
}

// return target.some(_ => arr.indexOf(_) > -1)
export const hasOneOf = (target, people) => {
  return target.some(function find(x) {
    const result = (x == people)
    return result
  })
}

// asyncRouterMap为一个数组，内部包含对象Object,item为遍历所有对象
export const getMenuByRouter = (list, role) => {
  const res = []
  forEach(list, item => {
    if (!item.meta || (item.meta && !item.meta.hidden)) {
      const obj = {
        ...item
      }
      if ((hasChild(item) || (item.meta && item.meta.showAlways)) && showThisMenuEle(item, role)) {
        obj.children = getMenuByRouter(item.children, role)
      }
      if (item.meta && item.meta.href) obj.href = item.meta.href
      if (showThisMenuEle(item, role)) {
        res.push(obj)
      } else { console.log('bye666666666666666666') }
    }
  })
  return res
}

// 第一个if判断该页面是否均有权限设置，如果页面的路由属性里面都没有roles属性，直接返回true,将该页面放入res里面
// 第二个if判断目标角色是否在对应的路由权限管理内部，若在其中，则加入res，反之则不加入
const showThisMenuEle = (item, role) => {
  if (item.meta && item.meta.roles && item.meta.roles.length) {
    if (hasOneOf(item.meta.roles, role)) {
      return true
    } else { return false }
  } else { return true }
}

export const hasChild = (item) => {
  return item.children && item.children.length !== 0
}

function hasPermission(roles, route) {
  if (route.meta && route.meta.interfaceName) {
    return roles.some(role => {
      if (route.meta.interfaceName == role.interfaceName) {
        if (role.isFlag > 0) {
          return true
        } else {
          return false
        }
      } else if (route.meta.interfaceName != role.interfaceName && role.sysMenuList && role.sysMenuList.length) {
        return hasPermission(role.sysMenuList, route)
      } else {
        return false
      }
    })
  } else {
    return true
  }
}
/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
export function filterAsyncRouter(asyncRouterMap, roles) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

/**
 *
 * @export
 * @param {*} asyncRouterMap
 * @param {*} roles
 * @returns
 */

function _filter(route) {
  return route.map(({ component, ...other }) => {
    return other
  })
}
export function filterRouteKeys(routes) {
  const cleanRoutes = routes.map(({ children, component, ...other }) => {
    if (children && children.length) {
      children = _filter(children)
    }
    return {
      children,
      ...other
    }
  })
  return cleanRoutes
}

